﻿using System;
using CoreEx.Services;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
namespace CoreEx.Database.Query.Expressions
{
    /// <summary>
    /// Provides the base class from which the classes that represent expression tree nodes are derived.
    /// </summary>
    public abstract class DbExpression
    {
        private static IServiceContainer _serviceContainer = ServiceLocator.Container;

        private static DbQueryTranslator _dbQueryTranslator;


        [ThreadStatic]
        protected static readonly DbExpressionFactory ExpressionFactory = new DbExpressionFactory();


        static DbExpression()
        {
            _dbQueryTranslator = _serviceContainer.GetService<DbQueryTranslator>("System.Data.SqlClient");
        }

        /// <summary>
        /// Gets the <see cref="DbExpressionType"/> of the <see cref="DbExpression"/>.
        /// </summary>
        public abstract DbExpressionType ExpressionType { get; }


        #region Operator Overloads

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="leftExpression">The left expression.</param>
        /// <param name="rightExpression">The right expression.</param>
        /// <returns>The result of the operator.</returns>
        public static DbExpression operator == (DbExpression leftExpression, DbExpression rightExpression)
        {
            return ExpressionFactory.Equal(leftExpression, rightExpression);
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="leftExpression">The left expression.</param>
        /// <param name="rightExpression">The right expression.</param>
        /// <returns>The result of the operator.</returns>
        public static DbExpression operator !=(DbExpression leftExpression, DbExpression rightExpression)
        {
            return ExpressionFactory.NotEqual(leftExpression, rightExpression);
        }



        #endregion

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return _dbQueryTranslator.Translate(this).Sql;
        }
        
    }
}
